﻿using System;
using System.Web;
using System.Data.Common;
using System.Data;


using Rmlife.Common;
using Rmlife.Data;
using Rmlife.Config;
using Rmlife.Model;
using Rmlife.Cache;

namespace Rmlife.Site
{
    /// <summary>
    /// 在线用户操作类
    /// </summary>
    public class OnlineUsers
    {
        private static object SynObject = new object();

        /// <summary>
        /// 获得在线用户总数量
        /// </summary>
        /// <returns>用户数量</returns>
        public static int GetOnlineAllUserCount()
        {
            int count = 0;//DatabaseProvider.GetInstance().GetOnlineAllUserCount();
            return count == 0 ? 1 : count;
        }

        /// <summary>
        /// 返回缓存中在线用户总数
        /// </summary>
        /// <returns>缓存中在线用户总数</returns>
        public static int GetCacheOnlineAllUserCount()
        {

            int count = Utils.StrToInt(Utils.GetCookie("onlineusercount"), 0);
            if (count == 0)
            {
                count = OnlineUsers.GetOnlineAllUserCount();
                Utils.WriteCookie("onlineusercount", count.ToString(), 3);
            }
            return count;

        }

        /// <summary>
        /// 清理之前的在线表记录(本方法在应用程序初始化时被调用)
        /// </summary>
        /// <returns></returns>
        public static int InitOnlineList()
        {
            return 0;// DatabaseProvider.GetInstance().CreateOnlineTable();
        }

        /// <summary>
        /// 复位在线表, 如果系统未重启, 仅是应用程序重新启动, 则不会重新创建
        /// </summary>
        /// <returns></returns>
        public static int ResetOnlineList()
        {
            try
            {
                // 取得在线表最后一条记录的tickcount字段 (因为本功能不要求特别精确)
                //int tickcount = DatabaseProvider.GetInstance().GetLastTickCount();
                // 如果距离现在系统运行时间小于10分钟
                if (System.Environment.TickCount < 600000 && System.Environment.TickCount > 0)
                {
                    return InitOnlineList();
                }
                return -1;
            }
            catch
            {
                try
                {
                    return InitOnlineList();
                }
                catch
                {
                    return -1;
                }
            }

        }

        /// <summary>
        /// 获得在线注册用户总数量
        /// </summary>
        /// <returns>用户数量</returns>
        public static int GetOnlineUserCount()
        {
            return 0;// DatabaseProvider.GetInstance().GetOnlineUserCount();
        }





        #region 根据不同条件查询在线用户信息


        /// <summary>
        /// 返回在线用户列表
        /// </summary>
        /// <param name="totaluser">全部用户数</param>
        /// <param name="guest">游客数</param>
        /// <param name="user">登录用户数</param>
        /// <param name="invisibleuser">隐身会员数</param>
        /// <returns>线用户列表</returns>
        public static DataTable GetOnlineUserList(int totaluser, out int guest, out int user, out int invisibleuser)
        {
            DataTable dt = null;// DatabaseProvider.GetInstance().GetOnlineUserListTable();

            // 统计用户
            DataRow[] dr = dt.Select("userid>0");
            if (dr == null)
            {
                user = 0;
            }
            else
            {
                user = dr.Length;
            }
            //统计隐身用户
            dr = dt.Select("invisible=1");
            if (dr == null)
            {
                invisibleuser = 0;
            }
            else
            {
                invisibleuser = dr.Length;
            }
            //统计游客
            if (totaluser > user)
            {
                guest = totaluser - user;
            }
            else
            {
                guest = 0;
            }
            //返回当前版块的在线用户表
            return dt;
        }



        #endregion



        #region 查看指定的某一用户的详细信息
        public static OnlineUserInfo GetOnlineUser(int olid)
        {
            IDataReader reader = null;// DatabaseProvider.GetInstance().GetOnlineUser(olid);
            OnlineUserInfo onlineuserinfo = null;
            if (reader.Read())
            {
                onlineuserinfo = LoadSingleOnlineUser(reader);
            }
            reader.Close();
            return onlineuserinfo;
        }

        /// <summary>
        /// 获得指定用户的详细信息
        /// </summary>
        /// <param name="userid">在线用户ID</param>
        /// <param name="password">用户密码</param>
        /// <returns>用户的详细信息</returns>
        private static OnlineUserInfo GetOnlineUser(int userid, string password)
        {
            DataTable dt = null;// DatabaseProvider.GetInstance().GetOnlineUser(userid, password);

            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                OnlineUserInfo onlineuserinfo = LoadSingleOnlineUser(dr);
                dt.Dispose();
                return onlineuserinfo;
            }
            return null;
        }


        /// <summary>
        /// 获得指定用户的详细信息
        /// </summary>
        /// <returns>用户的详细信息</returns>
        private static OnlineUserInfo GetOnlineUserByIP(int userid, string ip)
        {
            DataTable dt = null;// DatabaseProvider.GetInstance().GetOnlineUserByIP(userid, ip);
            if (dt.Rows.Count > 0)
            {
                OnlineUserInfo oluser = LoadSingleOnlineUser(dt.Rows[0]);
                dt.Dispose();
                return oluser;

            }
            return null;


        }

        /// <summary>
        /// 检查在线用户验证码是否有效
        /// </summary>
        /// <param name="olid">在组用户ID</param>
        /// <param name="verifycode">验证码</param>
        /// <returns>在组用户ID</returns>
        public static bool CheckUserVerifyCode(int olid, string verifycode)
        {
            return false;// DatabaseProvider.GetInstance().CheckUserVerifyCode(olid, verifycode, WebUtils.CreateAuthStr(4, false));
        }

        #endregion


        #region 添加新的在线用户
        /// <summary>
        /// 执行在线用户向表及缓存中添加的操作。
        /// </summary>
        /// <param name="onlineuserinfo">在组用户信息内容</param>
        /// <returns>添加成功则返回刚刚添加的olid,失败则返回0</returns>
        private static int Add(OnlineUserInfo onlineuserinfo, int timeout)
        {
            return 0;// DatabaseProvider.GetInstance().AddOnlineUser(onlineuserinfo, timeout, GeneralConfigs.GetConfig().Deletingexpireduserfrequency);
        }


        /// <summary>
        /// Cookie中没有用户ID或则存的的用户ID无效时在在线表中增加一个游客.
        /// </summary>
        public static OnlineUserInfo CreateGuestUser(int timeout)
        {
            OnlineUserInfo onlineuserinfo = new OnlineUserInfo();

            onlineuserinfo.Userid = -1;
            onlineuserinfo.Username = "游客";
            onlineuserinfo.Password = "";
            onlineuserinfo.Ip = WebReq.GetIP();
            onlineuserinfo.Verifycode = WebUtils.CreateAuthStr(4, false);
            onlineuserinfo.Lastupdatetime = Utils.GetDateTime();
            onlineuserinfo.Groupid = 0;
            onlineuserinfo.Adminid = 0;

            int olid = Add(onlineuserinfo, timeout);
            onlineuserinfo.Olid = olid;

            return onlineuserinfo;
        }
        /// <summary>
        /// 设置用户在线状态
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <param name="ionlinestate">在线状态，１在线</param>
        /// <returns></returns>
        public static int SetUserOnlineState(int uid, int ionlinestate)
        {
            return DbHelper.ExecuteNonQuery(CommandType.Text, string.Format("UPDATE [{0}tAccount] SET [ionlinestate]={1},[dtLastUpdate]=GETDATE() WHERE [iAccountid]={2}", BaseConfigs.GetTablePrefix, ionlinestate, uid));
        }


        /// <summary>
        /// 删除符合条件的一个或多个用户信息
        /// </summary>
        /// <returns>删除行数</returns>
        public static int DeleteRowsByIP(string ip)
        {
            DbParameter[] parms = {
									   DbHelper.MakeInParam("@ip",(DbType)SqlDbType.VarChar,15,ip)
								   };
            DbHelper.ExecuteNonQuery(CommandType.Text, "UPDATE [" + BaseConfigs.GetTablePrefix + "tAccount] SET [ionlinestate]=0,[dtLastUpdate]=GETDATE() WHERE [iAccountid] IN (SELECT [iuserid] FROM [" + BaseConfigs.GetTablePrefix + "tonline] WHERE [iuserid]>0 AND [sip]=@ip)", parms);
            if (ip != "0.0.0.0")
            {
                return DbHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM [" + BaseConfigs.GetTablePrefix + "tonline] WHERE [iuserid]=-1 AND [sip]=@ip", parms);
            }
            return 0;
        }

        /// <summary>
        /// 删除在线表中指定在线id的行
        /// </summary>
        /// <param name="olid">在线id</param>
        /// <returns></returns>
        public static int DeleteRows(int olid)
        {
            return DbHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM [" + BaseConfigs.GetTablePrefix + "tonline] WHERE [iolid]=" + olid.ToString());
        }

        #endregion

        #region Helper
        private static OnlineUserInfo LoadSingleOnlineUser(IDataReader reader)
        {
            OnlineUserInfo info = new OnlineUserInfo();
            info.Olid = Int32.Parse(reader["iolid"].ToString());
            info.Userid = Int32.Parse(reader["iuserid"].ToString());
            info.Ip = reader["sip"].ToString();
            info.Username = reader["susername"].ToString();
            info.Password = reader["spassword"].ToString();
            info.Lastupdatetime = reader["dtlastupdatetime"].ToString();
            info.Verifycode = reader["sverifycode"].ToString();
            info.Groupid = Int32.Parse(reader["iGroupid"].ToString());
            info.Adminid = Int32.Parse(reader["iadminid"].ToString());

            return info;
        }

        private static OnlineUserInfo LoadSingleOnlineUser(DataRow dr)
        {
            OnlineUserInfo info = new OnlineUserInfo();
            info.Olid = Int32.Parse(dr["iolid"].ToString());
            info.Userid = Int32.Parse(dr["iuserid"].ToString());
            info.Ip = dr["sip"].ToString();
            info.Username = dr["susername"].ToString();
            info.Password = dr["spassword"].ToString();
            info.Lastupdatetime = dr["dtlastupdatetime"].ToString();
            info.Verifycode = dr["sverifycode"].ToString();
            info.Groupid = Int32.Parse(dr["iGroupid"].ToString());
            info.Adminid = Int32.Parse(dr["iadminid"].ToString());

            return info;
        }
        #endregion


    }
}
